const router = require('koa-router')()
const { login,register,countUser,getDetail,updateUser } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')

router.prefix('/api/user')

router.post('/login', async function (ctx, next) { 
    const { username, password } = ctx.request.body
    const data = await login(username, password)
    if (data.username) {
        // 设置 session
        ctx.session.username = data.username
        ctx.body = new SuccessModel(data,'登录成功') 
    }else{
		ctx.body = new ErrorModel(data,'登录失败') 
	}
}) 

router.post('/register', async function (ctx, next) { 
    const { username, password } = ctx.request.body
    const check = await countUser(username)
	if(check > 0){
		ctx.body = new ErrorModel('帐号已存在') 
		return
	}	
    const data = await register(username, password)
    if (data.id) { 
		data.username = username
        ctx.body = new SuccessModel(data,'注册成功') 
    }else{
		ctx.body = new ErrorModel('注册失败') 
	}
}) 

router.post('/detail', async function (ctx, next) { 
    const {userId} = ctx.request.body
    const data = await getDetail(userId)
    if (data.username) {
        ctx.body = new SuccessModel(data) 
    }else{
		ctx.body = new ErrorModel(data,'查询失败') 
	}
})  

router.post('/update',  async function (ctx, next) {
    const data = await updateUser(ctx.request.body)
    if (data) {
        ctx.body = new SuccessModel('更新成功')
    } else {
        ctx.body = new ErrorModel('更新失败')
    }
})

router.post('/exit', async function (ctx, next) { 
	ctx.session.username = ''
	ctx.body = new SuccessModel('退出成功') 
}) 
module.exports = router